#ifndef _MY_CLOUD
#define _MY_CLOUD
#include"data.hpp"
#define BACKUP_FILE "./backup.dat"
#define BACKUP_DIR "./backup"
#include"httlib.h"
#include<Windows.h>
namespace cloud {
#define SERVER_IP "192.168.183.132"
#define SERVER_PORT 9090
	class Backup {
	private:
		std::string _back_dir;
		DataManager* _data;
	public:
		Backup(const std::string& back_dir, const std::string& back_file) :
			_back_dir(back_dir){
			_data = new DataManager(back_file);
		}
		std::string GetFileIdentfier(const std::string& filename) {
			FileUtil fu(filename);
			std::stringstream ss;
			ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.LastTime();
			 return ss.str();
		}
		bool Upload(const std::string &filename) {
			//1.获取文件数据
			FileUtil fu(filename);
			std::string body;
			fu.GetContent(&body);

			//2.搭建http客户端上传文件数据
			httplib::Client client(SERVER_IP, SERVER_PORT);
			httplib::MultipartFormData item;
			item.content = body;
			item.filename = fu.FileName();
			item.name = "file";
			item.content_type = "application/octet-stream";
			httplib::MultipartFormDataItems items;
			items.push_back(item);
			auto  res = client.Post("/upload", items);
			if (!res || res->status != 200) {
				return false;
			}
			return true;
		}

		bool IsNeedUpload(const std::string filename) {//文件是新增或者被修改了(标识不同)
			std::string id;
			if (_data->GetOneByKey(filename, &id) != false) {
				//有历史信息
				std::string new_id = GetFileIdentfier(filename);
				if (new_id == id) {//文件没有被修改过，不需要重新上传
					return false;
				}
				
			}
			FileUtil fu(filename);
			if (time(NULL) - fu.LastTime() < 3) {
				//三秒没被修改
				return false;
			}
			return true;
		}

		bool Runmodule() {
			while (1) {
				//1.获取指定文件夹所有文件
				FileUtil fu(_back_dir);
				std::vector<std::string>arry;
				fu.ScanDirectory(&arry);
				//2.逐个判断文件是否上传
				for (auto& a : arry) {
					if (IsNeedUpload(a) == false) {
						continue;
					}
					if (Upload(a) == true) {
						_data->Insert(a, GetFileIdentfier(a));//新增文件备份信息
					}
				}
				Sleep(1);
			}
		}

	};


}


#endif // !_MY_CLOUD

